<?php

namespace App\Models\Sgdzz;

use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class OrderDetailLog extends Model
{
    protected $table = 'game_sgdzz_order_detail_log';
    
    const 
        UNPAY_NO = 0,   //正常
        UNPAY_YES = 1;  //撤销

    /**
     * 获取某期下单详情
     * @param $issue
     *
     * @return mixed
     */
    public static function getOrderDetail($issue) {
        return self::where('issue', $issue)->where('unpay', self::UNPAY_NO)->orderBy('id', 'DESC')->get()->toArray();
    }

    /**
     * 获取用户某期的下单详情
     * @param $issue
     * @param $userId
     *
     * @return mixed
     */
    public static function getUserOrderDetail($issue, $userId) {
        return self::where('issue', $issue)->where('user_id', $userId)->where('unpay', self::UNPAY_NO)->orderBy('id', 'DESC')->get()->toArray();
    }

    /**
     * 按类型归类下单总额
     * @param $orderDetailItems
     *
     * @return array
     */
    public static function getOrderDetailSumByType($orderDetailItems) {
        
        $sumInfo = [
            Issue::TYPE_PINEAPPLE => 0,
            Issue::TYPE_BANANA => 0,
            Issue::TYPE_APPLE => 0,
        ];
        foreach( $orderDetailItems as $item ) {
            if( !isset( $sumInfo[$item['type']] ) ) {
                $sumInfo[$item['type']] = 0;
            }

            $sumInfo[$item['type']] += $item['gold'];
        }
        
        return $sumInfo;
    }

    /**
     * 获取用户某期购买数据总和，按水果类型合计
     * @param $issue
     * @param $userId
     *
     * @return array
     */
    public static function getUserOrderDetailSumByType($issue, $userId) {
        $orderDetailItems = self::getUserOrderDetail($issue, $userId);
        return self::getOrderDetailSumByType($orderDetailItems);
    }

    /**
     * 按类型归类每个用户的下单总额
     * @param $orderDetailItems
     *
     * @return array
     */
    public static function getOrderDetailSumByTypeUserId($orderDetailItems) {
        $sumInfo = [];
        foreach( $orderDetailItems as $item ) {
            if( !isset( $sumInfo[$item['type']] ) ) {
                $sumInfo[$item['type']] = [];
            }
            if( !isset( $sumInfo[$item['type']][$item['user_id']] ) ) {
                $sumInfo[$item['type']][$item['user_id']] = 0;
            }

            $sumInfo[$item['type']][$item['user_id']] += $item['gold'];
        }

        return $sumInfo;
    }

    /**
     * 获取用户当期中奖金额
     * @param $issue
     * @param $userId
     *
     * @return mixed
     */
    public static function getUserWinGold($issue, $userId, $winType) {
        $payGold = self::where('issue', $issue)
            ->where('user_id', $userId)
            ->where('type', $winType)
            ->where('unpay', self::UNPAY_NO)
            ->sum('gold');
        
        if(empty($payGold)) {
            return 0;
        }
        
        return $payGold * config('sgdzz.award_times');
    }

    /**
     * 每个用户某期购买总额
     * @param $issue
     * @param $userId
     *
     * @return int
     */
    public static function getUserPayGoldPerIssue( $issue, $userId ) {
        $payGold = self::where('issue', $issue)
            ->where('user_id', $userId)
            ->where('unpay', self::UNPAY_NO)
            ->sum('gold');
        
        if(empty($payGold)) {
            return 0;
        }
        
        return $payGold;
        
    }

    /**
     * 更新某期订单详情中奖标记
     * @param $issue
     * @param $winType
     *
     * @return mixed
     */
    public static function updateWinType($issue, $winType) {
        return OrderDetailLog::where('issue', $issue)
            ->where('unpay', 0)
            ->where('type', $winType)
            ->update([
                'is_win' => 1,
                'update_time' => time(),
            ]);
    }

    /**
     * 获取最近中奖详情（用户昵称、中奖类型、中奖金额）
     */
    public static function getLatestWinDetail($size = 30) {
        if(empty($size)) {
            $size = 30;
        }

        $winList = DB::select('select * from ( select user_id, issue, type, sum(gold) gold from game_sgdzz_order_detail_log where is_win = 1 and unpay = 0 group by user_id,issue order by issue desc limit ?) tmp group by user_id order by issue desc limit ?', [max(300, min(100, $size * 10)), $size]);
        $winList = json_decode(json_encode($winList), true);
        
        $userIds = array_column($winList, 'user_id');
        
        if(!empty($userIds)) {
            $listArr = User::whereIn('id', $userIds)->select('id', 'avatar', 'nickname')->get()->toArray();
            $listArrByUserId = [];
            foreach($listArr as $item) {
                $listArrByUserId[$item['id']] = $item;
            }
            
            foreach($winList as $key => $winItem) {
                $winList[$key]['nickname'] = $listArrByUserId[$winItem['user_id']]['nickname'];
                $winList[$key]['avatar'] = $listArrByUserId[$winItem['user_id']]['avatar'];
                $winList[$key]['gold'] = $winItem['gold'] * config('sgdzz.award_times');
            }
        }
        
        return $winList;
    }
}
